package com.fortune.controller;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fortune.base.BaseController;
import com.fortune.dto.excution.COrderExcution;
import com.fortune.dto.excution.ReturnDepositExcution;
import com.fortune.dto.excution.WechatProductExcution;
import com.fortune.dto.in.cOrder.*;
import com.fortune.enums.COrderEnum;
import com.fortune.enums.ReturnDepositEnum;
import com.fortune.enums.WechatProductEnum;
import com.fortune.exception.db.DeleteInnerErrorException;
import com.fortune.exception.db.InsertInnerErrorException;
import com.fortune.exception.db.UpdateInnerErrorException;
import com.fortune.service.COrderService;
import com.fortune.service.ReturnDepositService;
import com.fortune.service.WechatProductSevice;
import com.fortune.util.UUIDUtil;
import com.fortune.vo.cOrder.*;
import com.fortune.vo.cReturnDeposit.DealerList;
import com.fortune.vo.wechatProduct.ManufacturerProductList;
import com.fortune.vo.wechatProduct.Product;
import com.fortune.vo.wechatProduct.TerminalDiscount;
import com.fortune.vo.wechatProduct.VendorListVo;
import io.swagger.annotations.*;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fortune.base.BaseAPIExcution;
import com.fortune.common.paging.PagingData;

import springfox.documentation.annotations.ApiIgnore;


@Api(value = "wechat/cOrder", description = "客户订单", tags = {"微信小程序（客户）：订单相关"})
@RestController
@RequestMapping("wechat/cOrder")
@Validated
public class COrderController extends BaseController{
	@Autowired
	private COrderService cOrderService;

	@Autowired
	private WechatProductSevice wechatProductSevice;

	@Autowired
	private ReturnDepositService returnDepositService;
	@ApiOperation(value = "获取经销商列表", nickname = "dealerList", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@GetMapping(value = "dealerList",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<List<DealerList>> dealerList() {
		String userId = getUserId();
		List<DealerList> findDealerList = returnDepositService.findDealerList(userId);
		return new ReturnDepositExcution<List<DealerList>>(findDealerList, ReturnDepositEnum.FIND_SUCCESS);
	}

	@ApiOperation(value = "获取厂商列表", nickname = "manufacturerList", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true),
			@ApiImplicitParam(name="dealerId", value="经销商id",paramType="query",dataType="String")
	})
	@GetMapping(value = "manufacturerList",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<?> manufacturerList(@Validated @NotBlank(message="经销商id不能为空") String dealerId) {
		Map map = new HashMap();
		/*查询厂商列表*/
		List<VendorListVo> findVendorListVoList = cOrderService.findVendorListVoList(dealerId);
		map.put("findVendorListVoList",findVendorListVoList);
		/*获取自营*/
		String findAcountDid = cOrderService.findAcountDid(dealerId);
		if(Integer.parseInt(findAcountDid) > 0){
			map.put("zy","自营");
		}
		return new COrderExcution<Map>(map, COrderEnum.FIND_SUCCESS);
	}

	@ApiOperation(value = "获取商品列表", nickname = "cOrderProducts", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true),
			@ApiImplicitParam(name="did", value="经销商id",paramType="query",dataType="string")
	})
    @GetMapping(value = "products",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<?> list(@Validated @NotBlank(message="经销商id不能为空") String did) {
		/*客户id*/
		String cid = getUserId();
		List<VendorId> vendorIds = wechatProductSevice.findVendorIdList(did);
		Map<String,List<Map<String,List<Product>>>> result = new HashMap<>();
		List<Map<String,List<Product>>> list = new ArrayList<>();
		result.put("List",list);
		Map<String,List<Product>> typeMap = new HashMap<>();
		list.add(typeMap);
		int j=0;
		/*厂商所有商品*/
		for (int q=0; q<vendorIds.size(); q++){
			VendorId vendorId1 = vendorIds.get(q);
			/*厂商id*/
			String vendorId = vendorId1.getMid();
			/*查询商品列表*/
			List<ManufacturerProductList> findManufacturerProductList = wechatProductSevice.findManufacturerProductList(vendorId);

			for (ManufacturerProductList manufacturerProductList : findManufacturerProductList){

				List<Product> product = manufacturerProductList.getProducts();
				for(Product product1 : product){
					String mpid = product1.getId();
					/*优惠政策*/
					TerminalDiscount findTerminalDiscount = wechatProductSevice.findTerminalDiscount(vendorId, mpid);
					if(findTerminalDiscount != null){
						product1.setPolicyId(findTerminalDiscount.getId());
						product1.setAchieveNum(findTerminalDiscount.getAchieveNum());
						product1.setGiftNum(findTerminalDiscount.getGiftNum());
					}
					/*客户批发价*/
					BigDecimal clientPrice = wechatProductSevice.clientPrice(did, cid, vendorId, mpid);
					if(clientPrice != null){
						product1.setRetailPrice(clientPrice);
					}
				}

				List<Product> products = new ArrayList<>();
				Product product2 = new Product();
				product2.setTypeName(manufacturerProductList.getName());
				products.add(product2);
				for (int i=0;i<product.size();i++){
					products.add(product.get(i));
				}
				j++;
				typeMap.put("A"+ String.valueOf(j),products);
			}
		}
		/*经销商自营商品*/
		List<ManufacturerProductList> findZYProductList = wechatProductSevice.findZYProductList(did);
		for(ManufacturerProductList manufacturerProductList : findZYProductList){
			List<Product> product = manufacturerProductList.getProducts();
			for(Product product1 : product){
				String mpid = product1.getId();
					/*优惠政策*/
				TerminalDiscount findTerminalDiscount = wechatProductSevice.findTerminalDiscount(did, mpid);
				if(findTerminalDiscount != null){
					product1.setPolicyId(findTerminalDiscount.getId());
					product1.setAchieveNum(findTerminalDiscount.getAchieveNum());
					product1.setGiftNum(findTerminalDiscount.getGiftNum());
				}
			}

			List<Product> products = new ArrayList<>();
			Product product2 = new Product();
			product2.setTypeName(manufacturerProductList.getName());
			products.add(product2);
			for (int i=0;i<product.size();i++){
				products.add(product.get(i));
			}
			j++;
			typeMap.put("A"+ String.valueOf(j),products);
		}
		/*return new WechatProductExcution<Map<String,List<Map<String,List<Product>>>>>(null, WechatProductEnum.FIND_RESULT_AIR);*/
		return new WechatProductExcution<Map<String,List<Map<String,List<Product>>>>>(result, WechatProductEnum.FIND_SUCCESS);
	}
	
	@ApiOperation(value = "提交订单", nickname = "cOrderSubmit", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PostMapping(value = "add",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<CorderSubmit> add(@Validated @RequestBody COrderSubmitDto addDto) {
		String did = addDto.getDid();
		List<COrderProductDto> products = addDto.getProducts();
		String id = UUIDUtil.get32UUID();//订单id
		String no = UUIDUtil.get32UUID();//订单编号
		CorderSubmit corderSubmit = new CorderSubmit();
		corderSubmit.setId(id);
		corderSubmit.setNo(no);

		String clientId = getUserId();;//客户id
		BigDecimal pTotalPrice = addDto.getpTotalPrice();//商品总钱数
		BigDecimal dTotalPrice = addDto.getdTotalPrice();//押金钱数
		int addCOrder = cOrderService.addCOrder(did, clientId, id, no, pTotalPrice, dTotalPrice);
		if(addCOrder < 0){
			throw new InsertInnerErrorException("添加失败！");
		}
		int a = 0;
		for(COrderProductDto cOrderProductDto : products){
			//int num = products.getNum();//总商品数量
			List<PurchaseGiftDto> sales = cOrderProductDto.getSales();//销售
			List<PurchaseGiftDto> gift = cOrderProductDto.getGift();//赠送
			//int backBox = products.getBackBox();//回空箱数量

			//销售
			for(int j = 0; j < sales.size(); j++){
				PurchaseGiftDto purchaseGiftDto = sales.get(j);
				String mid = purchaseGiftDto.getMid();
				String productId = purchaseGiftDto.getProductId();//商品ID
				int detailsNo = a + 1;
				a = detailsNo;
				float orderNum = purchaseGiftDto.getOrderNum();//订货数量
				BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
				String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
				float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
				BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
				BigDecimal price = purchaseGiftDto.getPrice();//商品金额
				BigDecimal tprice = dprice.add(price);
				int addCOrderDetails = cOrderService.addCOrderDetails(did, clientId, id, detailsNo, mid, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
				if(addCOrderDetails < 0){
					throw new InsertInnerErrorException("添加失败！");
				}
			}
			if(gift.size() > 0){
				//赠送
				for(int x = 0; x < gift.size(); x++){
					PurchaseGiftDto purchaseGiftDto = gift.get(x);
					String mid = purchaseGiftDto.getMid();
					String productId = purchaseGiftDto.getProductId();//商品ID
					int detailsNo = a + 1;
					float orderNum = purchaseGiftDto.getOrderNum();//订货数量
					BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
					String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
					float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
					BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
					BigDecimal price = purchaseGiftDto.getPrice();//商品金额
					BigDecimal tprice = dprice.add(price);
					int addCOrderDetailsByZS = cOrderService.addCOrderDetailsByZS(did, clientId, id, detailsNo, mid, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
					if(addCOrderDetailsByZS < 0){
						throw new InsertInnerErrorException("添加失败！");
					}
				}
			}
		}
		return new COrderExcution<CorderSubmit>(corderSubmit, COrderEnum.ADD_SUCCESS);
	}
	
	@ApiOperation(value = "编辑订单", nickname = "clientOrderEdit", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PostMapping(value = "edit",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> edit(@Validated @RequestBody CClientOrderEditDto editDto) {
		String clientId = getUserId();//客户id
		String did = editDto.getDid();//经销商id
		String orderId = editDto.getOrderId();//订单id
		BigDecimal pTotalPrice = editDto.getdTotalPrice();
		BigDecimal dTotalPrice = editDto.getdTotalPrice();
		int editOrder = cOrderService.editOrder(did, clientId,orderId, pTotalPrice, dTotalPrice);
		if(editOrder < 1){
			throw new UpdateInnerErrorException("编辑失败！");
		}
		int delOrder = cOrderService.delOrder(did, clientId, orderId);
		if(delOrder < 1){
			throw new DeleteInnerErrorException("删除失败！");
		}
		List<COrderProductEditDto> products = editDto.getProducts();
		int a = 0;
		for(COrderProductEditDto cOrderProductEditDto : products){
			//int num = products.getNum();//总商品数量
			List<PurchaseGiftDto> sales = cOrderProductEditDto.getSales();//销售
			List<PurchaseGiftDto> gift = cOrderProductEditDto.getGift();//赠送
			//int backBox = products.getBackBox();//回空箱数量

			//销售
			for(int j = 0; j < sales.size(); j++){
				PurchaseGiftDto purchaseGiftDto = sales.get(j);
				String mid = purchaseGiftDto.getMid();
				String productId = purchaseGiftDto.getProductId();//商品ID
				int detailsNo = a + 1;
				a = detailsNo;
				float orderNum = purchaseGiftDto.getOrderNum();//订货数量
				BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
				String policyId;
				if(purchaseGiftDto.getPolicyId() == "" || purchaseGiftDto.getPolicyId() == null){
					policyId = "无";
				}else{
					policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
				}
				float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
				BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
				BigDecimal price = purchaseGiftDto.getPrice();//商品金额
				BigDecimal tprice = dprice.add(price);
				int addCOrderDetails = cOrderService.addCOrderDetails(did, clientId, orderId, detailsNo, mid, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
				if(addCOrderDetails < 0){
					throw new InsertInnerErrorException("添加失败！");
				}
			}
			if(gift.size() != 0){
				//赠送
				for(int x = 0; x < gift.size(); x++){
					PurchaseGiftDto purchaseGiftDto = gift.get(x);
					String mid = purchaseGiftDto.getMid();
					String productId = purchaseGiftDto.getProductId();//商品ID
					int detailsNo = a + 1;
					float orderNum = purchaseGiftDto.getOrderNum();//订货数量
					BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
					String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
					float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
					BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
					BigDecimal price = purchaseGiftDto.getPrice();//商品金额
					BigDecimal tprice = dprice.add(price);
					int addCOrderDetailsByZS = cOrderService.addCOrderDetailsByZS(did, clientId, orderId, detailsNo, mid, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
					if(addCOrderDetailsByZS < 0){
						throw new InsertInnerErrorException("添加失败！");
					}
				}
			}
		}
		return new COrderExcution<Void>(null, COrderEnum.EDIT_SUCCESS);
	}
	
	/*@ApiOperation(value = "获取订单列表", nickname = "clientOrderList", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
		@ApiImplicitParam(name="page", value="第几页",paramType="query",dataType="int"),
		@ApiImplicitParam(name="length", value="每页容量",paramType="query",dataType="int"),
		@ApiImplicitParam(name="type", value="0未处理，1已批准，2已发货，3已收货，4已完成",paramType="query",dataType="int",allowableValues="0,1,2,3,4"),
		@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @GetMapping(value = "list",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<PagingData> list(@ApiIgnore @Validated ClientOrderListByTypeDto listDto) {


			//clientOrders.add(clientOrder);
			PagingData pagingData = new PagingData();
			pagingData.setData(clientOrders);
			return new COrderExcution<PagingData>(pagingData, COrderEnum.FIND_SUCCESS);
		}

		return new COrderExcution<PagingData>(null, COrderEnum.FIND_RESULT_AIR);
	}*/
	
	@ApiOperation(value = "获取已批准订单详情", nickname = "clientOrderDetail", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="dId", value="经销商id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @GetMapping(value = "detail",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<ClientOrderDetail> detail(@Validated @NotBlank(message="订单id不能为空") String orderId,@Validated @NotBlank(message="经销商id不能为空") String dId) {
		String clientId = getUserId();
		//String did = cOrderService.findClientDid(clientId);
		ClientOrderDetail findClientOrderDetail = cOrderService.findClientOrderDetail(dId, clientId, orderId);
		if(findClientOrderDetail == null){
			return new COrderExcution<ClientOrderDetail>(null, COrderEnum.FIND_RESULT_AIR);
		}
		String createTime = findClientOrderDetail.getCreateTime();
		findClientOrderDetail.setCreateTime(createTime.substring(0,19));
		String payTime = findClientOrderDetail.getPayTime();
		if(payTime != null){
			findClientOrderDetail.setPayTime(payTime.substring(0,19));
		}
		return new COrderExcution<ClientOrderDetail>(findClientOrderDetail, COrderEnum.FIND_SUCCESS);
	}

//	@ApiOperation(value = "获取已出库详情", nickname = "clientOutLibraryDetail", notes = "", tags = {"@郭阳"})
//	@ApiImplicitParams({
//			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
//			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
//	})
//	@GetMapping(value = "libraryDetail",
//			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<ClientOrderDetail> libraryDetail(@Validated @NotBlank(message="订单id不能为空") String orderId) {
		String clientId = getUserId();
		String did = cOrderService.findClientDid(clientId);
		ClientOrderDetail findClientOrderDetailByCk = cOrderService.findClientOrderDetailByCk(did, clientId, orderId);
		if(findClientOrderDetailByCk == null){
			return new COrderExcution<ClientOrderDetail>(null, COrderEnum.FIND_RESULT_AIR);
		}
		return new COrderExcution<ClientOrderDetail>(findClientOrderDetailByCk, COrderEnum.FIND_SUCCESS);
	}

//	@ApiOperation(value = "获取已收货详情", nickname = "clientReceiptDetail", notes = "", tags = {"@郭阳"})
//	@ApiImplicitParams({
//			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
//			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
//	})
//	@GetMapping(value = "receiptDetail",
//			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<ClientOrderDetails> receiptDetail(@Validated @NotBlank(message="订单id不能为空") String orderId) {
		String clientId = getUserId();
		String did = cOrderService.findClientDid(clientId);
		ClientOrderDetails findClientOrderDetailsBySH = cOrderService.findClientOrderDetailsBySH(did, clientId, orderId);
		if(findClientOrderDetailsBySH == null){
			return new COrderExcution<ClientOrderDetails>(null, COrderEnum.FIND_RESULT_AIR);
		}
		return new COrderExcution<ClientOrderDetails>(findClientOrderDetailsBySH, COrderEnum.FIND_SUCCESS);
	}

//	@ApiOperation(value = "获取已完成详情", nickname = "clientCarryDetail", notes = "", tags = {"@郭阳"})
//	@ApiImplicitParams({
//			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
//			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
//	})
//	@GetMapping(value = "carryDetail",
//			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<ClientOrderDetails> carryDetail(@Validated @NotBlank(message="订单id不能为空") String orderId) {
		String clientId = getUserId();
		String did = cOrderService.findClientDid(clientId);
		ClientOrderDetails findClientOrderDetailsByWC = cOrderService.findClientOrderDetailsByWC(did, clientId, orderId);
		if(findClientOrderDetailsByWC == null){
			return new COrderExcution<ClientOrderDetails>(null, COrderEnum.FIND_RESULT_AIR);
		}
		return new COrderExcution<ClientOrderDetails>(findClientOrderDetailsByWC, COrderEnum.FIND_SUCCESS);
	}
	
	@ApiOperation(value = "删除订单", nickname = "clientOrderDelete", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @DeleteMapping(value = "delete",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> delete(@Validated @NotBlank(message="订单id不能为空") String orderId){
		String clientId = getUserId();
		String did = cOrderService.findClientDid(clientId);
		int deleteCOrder = cOrderService.deleteCOrder(did, clientId, orderId);
		if(deleteCOrder < 0){
			return new COrderExcution<Void>(null, COrderEnum.DELETE_ERROR);
		}
		return new COrderExcution<Void>(null, COrderEnum.DELETE_SUCCESS);
	}

	@ApiOperation(value = "获取工单商品列表", nickname = "workOrderList", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@DeleteMapping(value = "workOrderList",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<List<WorkOrderList>> workOrderList(){
		String mid = getMId();
		List<WorkOrderList> findWorkOrderListList = cOrderService.findWorkOrderListList(mid);
		return new COrderExcution<List<WorkOrderList>>(findWorkOrderListList, COrderEnum.FIND_SUCCESS);
	}
}
